/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.wx.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.wx.entity.WxBusiness;
import com.jeesite.modules.wx.entity.WxBusinessGroupOrgConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.wx.entity.WxBusinessGroup;
import com.jeesite.modules.wx.dao.WxBusinessGroupDao;

import java.util.Arrays;
import java.util.List;

/**
 * 商家和组的对应关系表Service
 * @author wangjianxin
 * @version 2018-12-03
 */
@Service
@Transactional(readOnly=true)
public class WxBusinessGroupService extends CrudService<WxBusinessGroupDao, WxBusinessGroup> {

	@Autowired
	private WxBusinessService wxBusinessService;

	/**
	 * 获取单条数据
	 * @param wxBusinessGroup
	 * @return
	 */
	@Override
	public WxBusinessGroup get(WxBusinessGroup wxBusinessGroup) {
		return super.get(wxBusinessGroup);
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param wxBusinessGroup
	 * @return
	 */
	@Override
	public Page<WxBusinessGroup> findPage(Page<WxBusinessGroup> page, WxBusinessGroup wxBusinessGroup) {
		return super.findPage(page, wxBusinessGroup);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param wxBusinessGroup
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(WxBusinessGroup wxBusinessGroup) {
		super.save(wxBusinessGroup);
	}
	
	/**
	 * 更新状态
	 * @param wxBusinessGroup
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(WxBusinessGroup wxBusinessGroup) {
		super.updateStatus(wxBusinessGroup);
	}
	
	/**
	 * 删除数据
	 * @param wxBusinessGroup
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(WxBusinessGroup wxBusinessGroup) {
		super.delete(wxBusinessGroup);
	}


	/**
	 * 保存新的分组商家对应关系
	 * @param wxBusinessGroupOrgConfig
	 * @param officeCode
	 */
	@Transactional(readOnly=false,rollbackFor = Exception.class)
	public void saveEmpty(WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig, String officeCode){
		WxBusinessGroup saveBusinessGroup = new WxBusinessGroup();
		//主推商家ids
		saveBusinessGroup.setApplyBusinessIds(wxBusinessGroupOrgConfig.getWxBusinessGroup().getApplyBusinessIds());
		//机构
		saveBusinessGroup.setOfficeCode(officeCode);
		//分组id
		saveBusinessGroup.setConfigGroupId(Long.valueOf(wxBusinessGroupOrgConfig.getId()));
		this.save(saveBusinessGroup);
	}

	/**
	 * 解除商家在此分组
	 * @param groupId
	 * @param businessId
	 */
	@Transactional(readOnly=false,rollbackFor = Exception.class)
	public void removeBusinessId(Long groupId,String businessId){

		WxBusinessGroup wxBusinessGroup = new WxBusinessGroup();
		wxBusinessGroup.setConfigGroupId(groupId);
		List<WxBusinessGroup> wxBusinessGroupList = this.findList(wxBusinessGroup);
		if(CollectionUtil.isNotEmpty(wxBusinessGroupList)){
			WxBusinessGroup find = wxBusinessGroupList.get(0);
			String dbBusinessIds = find.getBusinessIds();
			//判空
			if(StringUtil.isNotEmpty(dbBusinessIds)){
				logger.info("解除分组中的商家获得ids={}",dbBusinessIds);
				if(dbBusinessIds.contains(businessId+",")){
					logger.info("商家存在形式,,,,");
					dbBusinessIds = dbBusinessIds.replace(businessId+",","");
				}else if(dbBusinessIds.contains(businessId)){
					logger.info("商家存在形式 一个");
					dbBusinessIds = dbBusinessIds.replace(businessId,"");
				}else{
					logger.info("没有在分组ids中找到商家={}",businessId);
				}
				find.setBusinessIds(dbBusinessIds);
				this.save(find);
			}

		}else{
			logger.error("根据groupId={}解除商家在此分组，未找到wxBusinessGroup",groupId);
		}

	}

	/**
	 * 处理商家排名
	 * @param groupId
	 */
	public JSONObject getSort(Long groupId){
		//返回的商家array
		JSONArray jsonArrayBusiness = new JSONArray();
		//主推商家
		JSONArray jsonArrayMainBusiness = new JSONArray();

		//单独一行的数据，商家序使用
		JSONArray nextJsonArrayBusiness = new JSONArray();
		//是否排序
		Boolean isSort = false;
		int maxlen = 0;
		String[] firstBusinessNameArray;

		WxBusinessGroup wxBusinessGroup = new WxBusinessGroup();
		wxBusinessGroup.setConfigGroupId(groupId);
		List<WxBusinessGroup> wxBusinessGroupList = this.findList(wxBusinessGroup);
		if(CollectionUtil.isNotEmpty(wxBusinessGroupList)){
			WxBusinessGroup findBusinessGroup = wxBusinessGroupList.get(0);
			//获得分组的排序商家
			String sortBusinessIds = findBusinessGroup.getSortBusinessIds();
			//获得分组的商家
			String businessIds = findBusinessGroup.getBusinessIds();
			//获得分组的主推商家
			String applyBusinessIds = findBusinessGroup.getApplyBusinessIds();
			//需要排序
			isSort = true;
			if(StringUtil.isNotEmpty(sortBusinessIds)){
				firstBusinessNameArray = sortBusinessIds.split(",");
				//根据firstBusinessNameArray size算出maxlen需要折行的大小
				int size = firstBusinessNameArray.length;
				if(size < 10){
					//排行榜小于10个不展示
				}else{
					maxlen = 4;
					for(int i= 0;i<size;i++){
						WxBusiness wxBusiness = new WxBusiness();
						wxBusiness.setId(firstBusinessNameArray[i].trim());
						List<WxBusiness> wxBusinessList = wxBusinessService.findList(wxBusiness);
						if(CollectionUtil.isNotEmpty(wxBusinessList)){
							WxBusiness temp = wxBusinessList.get(0);
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("businessId",temp.getId());
							jsonObject.put("businessName",temp.getName());
							jsonObject.put("businessPic",temp.getPic());
							if(i > maxlen){
								//需要添加到下一行的数据array中
								nextJsonArrayBusiness.add(jsonObject);
							}else{
								jsonArrayBusiness.add(jsonObject);
							}
						}
					}

				}
			}

			//商家,注意如果选了排序的商家，注意去重
			if(StringUtils.isNotEmpty(businessIds)){
				String[] businessArray = businessIds.split(",");
				int len = businessArray.length;
				for(int i = 0;i<len;i++){
					String businessId = businessArray[i];
					WxBusiness wxBusiness = wxBusinessService.get(businessId);
					if(null != wxBusiness){
						String businessName = wxBusiness.getName().trim();
						JSONObject jsonObject = new JSONObject();
						jsonObject.put("businessId",businessId);
						jsonObject.put("businessName",businessName);
						jsonObject.put("businessPic",wxBusiness.getPic());

						//去重复，如果有排序的商家
						if(isSort){
							if(jsonArrayBusiness.contains(jsonObject) || nextJsonArrayBusiness.contains(jsonObject)){
								continue;
							}
						}
						jsonArrayBusiness.add(jsonObject);
					}
				}

				if(isSort){
					//算出折行
					int nextLen = 0;
						nextLen = jsonArrayBusiness.size() + nextJsonArrayBusiness.size();
						nextLen = (nextLen / 2) + 1;
					//排序商家添加
					jsonArrayBusiness.addAll(nextLen,nextJsonArrayBusiness);
				}
			}

			//会员卡，主推商家
			if(StringUtils.isNotEmpty(applyBusinessIds)){

				String[] mainBusinessArray = applyBusinessIds.split(",");
				int len = mainBusinessArray.length;

				for(int i=0;i<len;i++){

					String id = mainBusinessArray[i];
					WxBusiness wxBusiness = wxBusinessService.get(id);
					if(null != wxBusiness){

						JSONObject jsonObject = new JSONObject();
						jsonObject.put("mainBusinessId",id);
						jsonObject.put("mainBusinessPic",wxBusiness.getPic());
						jsonObject.put("mainBusinessName",wxBusiness.getName());
						jsonObject.put("mainBusinessAddress",wxBusiness.getAddress());
						jsonObject.put("mainBusinessVipCardImg",wxBusiness.getVipCardImg());
						jsonObject.put("mainBusinessPhone",wxBusiness.getPhone());

						jsonArrayMainBusiness.add(jsonObject);
					}
				}
			}

		}

		JSONObject result = new JSONObject();
		result.put("business",jsonArrayBusiness);
		result.put("mainBusiness",jsonArrayMainBusiness);

		return result;
	}


}